/**
 * Created by Loriling on 2015/5/13.
 * 计时器
 */
define(function(){
    var Timer = function(interval){
        this.intervalToken = -1;
        this.interval = interval;
        this.running = false;
        this.callbacks = [];
    };
    Timer.create = function(interval, callback){
    	var timer = new Timer(interval);
    	timer.addCallback(callback);
    	return timer;
    };
    Timer.prototype = {
        start : function(){
            var timer = this;
            if(!timer.running){
                timer.running = true;
                timer.intervalToken = setInterval(function() {
                    timer.callbacks.forEach(function(cb){
                        if($.isFunction(cb)){
                            try{
                                cb();
                            }catch(e){}
                        }
                    });
                }, timer.interval);
            }
        },
        
        stop : function(){
            this.running = false;
            if(this.intervalToken != -1){
                clearInterval(this.intervalToken);
            }
        },
        
        reset : function(){
            this.stop();
            this.start();
        },
        
        addCallback : function(callback){
            this.callbacks.push(callback);
        }
    };

    return Timer;
});
